//
//  XTAuthorizeViewController.swift
//  HrenryWeibo
//
//  Created by 熊涛 on 16/5/12.
//  Copyright © 2016年 熊涛. All rights reserved.
//

import UIKit
import SVProgressHUD

class XTAuthorizeViewController: UIViewController {

    

    
    
    //MARK: - lifecycle
    override func loadView() {
        
        //将view设置成webView
        view = webView
        //设置代理
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        
        // https://api.weibo.com/oauth2/authorize
        
        let str = authorizeURL + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let urlStr = NSURL(string: str)
        let request = NSURLRequest(URL: urlStr!)
        webView.loadRequest(request)
        
        navigationItem.title = "登录"
        
        self.view.backgroundColor = UIColor.whiteColor()
        //设置导航栏
        //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fillBtnAction")
        //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBtnAction")
        
        
        //添加加载的效果
//        SVProgressHUD.showInfoWithStatus("正在加载中...") //感叹号,会自动关闭
//        SVProgressHUD.showProgress(0.5) //进度的效果 //不会自己消失
        SVProgressHUD.showWithStatus("正在加载中...") //旋转的效果  不会自己消失
        
    }
    
    

    //MARK: - 按钮点击事件
    func fillBtnAction() {
        XTPrint(items: "点击了填充按钮")
        //webView调用JS代码
        let jsString = "document.getElementById('userId').value = '1002153267@qq.com';document.getElementById('passwd').value = 'xt5090948'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    func cancelBtnAction() {
        XTPrint(items: "点击了取消按钮")
        //点击取消按钮 取消动画效果
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    //MARK: - 懒加载
    lazy var webView : UIWebView = UIWebView()
    
}

//MARK: - 代理方法
extension XTAuthorizeViewController : UIWebViewDelegate {
    
    //webView已经加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        //加载完成 取消加载效果
        SVProgressHUD.dismiss()
    }
    
    //    是否开始加载这个request
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //        XTPrint(items: "是否开始加载")
        //        XTPrint(items: "shouldStartLoadWithRequest \(request)")
        //点击授权: http://www.baidu.com/?code=ef9811c455051a8a73fd6ee671ca90f5
        //点击取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        
        //根据前缀判断是否加载网页
        //如果是回调的地址,就不加载网页,返回false,如果不是回调的地址,就加载,返回true
        if ((request.URL?.absoluteString.hasPrefix(redirect_uri)) == false) {
            
            return true
        }
        
        //这个query 取的是url的?后面的部分 返回的是字符串
        let query = request.URL?.query
        let coding = "code="
        if query?.hasPrefix(coding) == true {
            //点击授权
            // substringFromIndex 截取下标往后的字符串
            let code = (query! as NSString).substringFromIndex(coding.characters.count)
            
            //发送请求获取AccessToken,字典转模型,保存到沙盒中
            XTUserAccountViewModel.sharedInstance.loadAccessToken(code, callBack: { (error) -> () in
                if error != nil {
                    //出现错误
                    XTPrint(items: "出现了错误:\(error)")
                    SVProgressHUD.showErrorWithStatus("您的网络不给力")
                    
                    //模拟延迟,延迟一秒
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                        
                        self.cancelBtnAction()
                    })
                    
                }else {
                    //转换成功,没有错误
                    self.cancelBtnAction()
//                    XTUserAccountViewModel.sharedInstance.isLogin
                    Delegate.changeRootViewController(XTWelcomViewController())
                }
            })
            
        }else {
            //点击取消--就dismis这个界面
            cancelBtnAction()
        }
        
        return false
    }
    

}


